package com.tinygray.arraylist;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @Author: tinygray
 * @Description: 公众号:Madison龙少，关注我你会越来越优秀。
 * @className: ArrayListDemo
 * @create: 2021-05-07 23:11
 */

/**
 * list、set、map线程不安全问题
 */
public class ArrayListDemo {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        Map<String, String> map1 = new ConcurrentHashMap<>();
        for (int i = 0; i < 30; i++) {
            new Thread(()->{
                map1.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0, 8));
                System.out.println(map1.toString());
            }).start();
        }
    }

    private static void setNotSafe() {
        /**
         * HashSet 底层是HashMap
         *
         * add()方法：调用HashMap的put()方法 value是present 常量
         *
         * 为什么value是present常量而不是null
         *      ：因为在remove的时候需要根据 present是判断 是否删除成功  如果开始的时候设置成null 则无法区分
         */
        Set<String> hashSet = new HashSet<>();

        //解决线程不安全问题 CopyOnWriteArraySet  其实底层还是CopyOnWriteArrayList
        Set<String> copyOnWriteArraySet = new CopyOnWriteArraySet<>();
        for (int i = 0; i < 30; i++) {
            new Thread(()->{
                copyOnWriteArraySet.add(UUID.randomUUID().toString().substring(0, 8));
                System.out.println(copyOnWriteArraySet);
            },String.valueOf(i)).start();
        }
    }

    private static void listNotSafe() {
        List<String> strings = Arrays.asList("a", "b", "c");
        strings.forEach(System.out::println);
        List<String> list = new ArrayList<>();
        //方法1
        Vector<String> vector = new Vector<>();
        //方法2
        List<String> synchronizedList = Collections.synchronizedList(new ArrayList<>());
        //方法3
        CopyOnWriteArrayList<String> copyOnWriteArrayList = new CopyOnWriteArrayList<>();
        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                copyOnWriteArrayList.add(UUID.randomUUID().toString().substring(0, 8));
                System.out.println(copyOnWriteArrayList);
            }, String.valueOf(i)).start();
        }
    }
}
